package com.founder.jobhandler;

import com.founder.service.FianceAliService;
import com.founder.utils.ServiceUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@JobHandler(value="alipayJob")
@Service
public class AlipayJobHandler extends IJobHandler {

    @Autowired
    FianceAliService fianceAliService;

    @Override
    public ReturnT<String> execute(String param) {
        XxlJobLogger.log("开始支付宝作业");

        String args[] = param.split("\\,");
        XxlJobLogger.log("解析参数：" + param);

        String mchId = args[0];
        XxlJobLogger.log("任务附加参数[商户号]:" + mchId);

        String prefix = args[1];
        XxlJobLogger.log("任务附加参数[prefix]:" + prefix);

        String suffix = args[2];
        XxlJobLogger.log("任务附加参数[suffix]:" + suffix);

        String ftpOpen = args[3];
        XxlJobLogger.log("任务附加参数[ftpOpen]:" + ftpOpen);

        String ftpHome = args[4];
        XxlJobLogger.log("任务附加参数[ftpHome]:" + ftpHome);

        String subsys = args[5];
        XxlJobLogger.log("任务附加参数[subsys]:" + subsys);

        String billDate = DateFormatUtils.format(DateUtils.addDays(new Date(), -2),"yyyyMMdd");
        String postData = "&date="+billDate+"&mchId="+mchId+"&prefix="+prefix+"&suffix="+suffix+"&ftpOpen="+ftpOpen+"&ftpHome="+ftpHome+"&subsys="+subsys;

        XxlJobLogger.log("【支付宝】准备下载" + billDate + "的对账单。");
        XxlJobLogger.log("访问地址：http://" + ServiceUtil.getIP() + ":" + ServiceUtil.getPort() + "/bill/zfb?service=pp.trade.bill" + postData);

        try {
            fianceAliService.generateAl(mchId, billDate, prefix, suffix, ftpOpen, ftpHome, subsys);
            return ReturnT.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            XxlJobLogger.log(e.getMessage());
            return new ReturnT<>(500, e.getMessage());
        }
    }

}
